package com.jushu.storbox.util.identity;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

import com.jushu.storbox.util.LogUtil;

public class FileSha1Identity extends AbsFileIdentity {

	public FileSha1Identity(String filePath) {
		super(filePath);
	}
	
	public FileSha1Identity(String filePath, IidentityCallback callback) {
		super(filePath, callback);
	}

	private String computeShal1() {
		FileInputStream in = null;
		try {
			in = new FileInputStream(innerFile);
			MessageDigest messagedigest = MessageDigest.getInstance("SHA-1");

			byte[] buffer = new byte[1024 * 128];
			int len = 0;
			double currentProgress = 0;
			double progress = 0;
			double oldProgress = 0;

			while ((len = in.read(buffer)) > 0) {
				messagedigest.update(buffer, 0, len);
				currentProgress += len;
				oldProgress = currentProgress * 100 / innerFile.length();
				if ((int) progress != (int) oldProgress) {
					progress = oldProgress;
					IdentityCallback.onProgress((int) progress,
							(long) currentProgress, innerFile.length());// onProgress
				}
			}
			identity = byte2hex(messagedigest.digest());
			IdentityCallback.onSuccess(identity);

		} catch (Exception e) {
			LogUtil.e(TAG,e.getMessage());
			IdentityCallback.onFailure(e.fillInStackTrace());
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LogUtil.e(TAG,e.getMessage());
				}
			}
		}
		return identity;
	}

	@Override
	protected String doComputeIdentity(){
		identity = computeShal1();
		return identity;
	}
}
